package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CanalEventListener
public class SpuListener {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodsUp(CanalEntry.EventType eventType,CanalEntry.RowData rowData){
        //改变之前的数据封装到Map
        Map<String,String> beforeMap = new HashMap<>();
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        beforeColumnsList.forEach((s)->beforeMap.put(s.getName(),s.getValue()));

        //改变之后的数据封装
        Map<String,String> afterMap = new HashMap<>();
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        afterColumnsList.forEach((s)->afterMap.put(s.getName(),s.getValue()));

        //商品本身有已经上架的。所以要判断找到最新上架的产品
        if (beforeMap.get("is_marketable").equals("0") && afterMap.get("is_marketable").equals("1")){
            System.out.println("发送的数据为:"+afterMap.get("id"));
            System.out.println("发送前的数据为："+beforeMap.get("id"));
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",afterMap.get("id"));
        }

        //商品本身有已经下架的。所以要判断找到最新上架的产品 ---下架产品发送消息
        if (beforeMap.get("is_marketable").equals("1") && afterMap.get("is_marketable").equals("0")){
            System.out.println("发送的数据为:"+afterMap.get("id"));
            System.out.println("发送前的数据为："+beforeMap.get("id"));
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",afterMap.get("id"));
        }

        //获取最新审核通过商品 status 0->1
        if (beforeMap.get("status").equals("0") && afterMap.get("status").equals("1")){
            System.out.println("发送的数据为:"+afterMap.get("id"));
            System.out.println("发送前的数据为："+beforeMap.get("id"));
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",afterMap.get("id"));
        }
    }
}
